package com.repast.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class DateUtils {

	private static DateUtils instance = new DateUtils();
	
	public static String getClientIp(HttpServletRequest request) {
	       String ip = request.getHeader("x-forwarded-for");
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	    	   ip = request.getHeader("Proxy-Client-IP");
	       }
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	    	   ip = request.getHeader("WL-Proxy-Client-IP");
	       }
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getRemoteAddr();
	       }
	       return ip;
	} 
	
	//时间转String1
	public static String formatDateTime(Date date,String dft){
		String rslt="";
        SimpleDateFormat sdf = new SimpleDateFormat();
        if(dft.equals("short")){
        	dft="yyyy-MM-dd";
        }else if(dft.equals("long")){
        	dft="yyyy-MM-dd HH:mm:ss";	        	
        }else if(dft.equals("middle")){
        	dft="yyyy-MM-dd HH:mm";	     
        }
        sdf.applyPattern(dft);
        rslt=sdf.format(date);
		return rslt;
	}
	//时间转String2
	public static String formatDateTime(String date,String dft){
		String rslt=date;
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
        Date d=null;
        try {
			d=sdf.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(d!=null)rslt=formatDateTime(d,dft);
		return rslt;
	}
	
	public static String getSafeString(String str){
		String rslt=str;
		rslt.replaceAll("<", "��");
		rslt.replaceAll(">", "��");
		rslt.replaceAll("\"", "&quot;");
		rslt.replaceAll("'", "&acute;");
		rslt.replaceAll(";", "��");
		rslt.replaceAll("#", "��");
		rslt.replaceAll("$", "");
		rslt.replaceAll("=", "��");
		rslt.replaceAll("(", "��");
		rslt.replaceAll(")", "��");
		rslt.replaceAll("%", "��");
		return rslt;
	}
	
   
   
    public static String cleanHTMLAndWord(String inputString) {
        String htmlStr = inputString; //��html��ǩ���ַ���
        String textStr ="";
        java.util.regex.Pattern p_script;
        java.util.regex.Matcher m_script;
        java.util.regex.Pattern p_style;
        java.util.regex.Matcher m_style;
        java.util.regex.Pattern p_html;
        java.util.regex.Matcher m_html;          
        java.util.regex.Pattern p_ba;
        java.util.regex.Matcher m_ba;
        
        try {
            String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; //����script��������ʽ{��<script[^>]*?>[\\s\\S]*?<\\/script> }
            String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; //����style��������ʽ{��<style[^>]*?>[\\s\\S]*?<\\/style> }
            String regEx_html = "<[^>]+>"; 
            String patternStr = "\\s+";
            
            p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); 

            p_style = Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); 
         
            p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); 
            
            p_ba = Pattern.compile(patternStr,Pattern.CASE_INSENSITIVE);
            m_ba = p_ba.matcher(htmlStr);
            htmlStr = m_ba.replaceAll(""); 
            
            htmlStr = htmlStr.replaceAll("&nbsp;","");
         textStr = htmlStr;
         
        }catch(Exception e) {
                    System.err.println("Html2Text: " + e.getMessage());
        }          
        return textStr;
     }

    public static String cleanHTML(String str){
    	return cleanHTMLAndWord(str);
    }
    
   
	public static String getRandom(long start,long end){
		String s = String.valueOf(start+(long)(Math.random() * end));
		return s;
	}
	
	
    public static String getRootPath(){
        return instance.getServerRealPath();
	}
    
    private String getServerRealPath(){
        String rslt = null;
       try {
			rslt = this.getClass().getResource("").toURI().getPath().substring(1);
		} catch (URISyntaxException e) {
			e.printStackTrace();
			rslt = this.getClass().getResource("").getPath().substring(1).replaceAll("%20", " ");
		}
		rslt=rslt.replace('\\','/');
		rslt=rslt.substring(0,rslt.indexOf("/WEB-INF/classes/com/chunqiu/")+1);
		String sysName=System.getProperty("os.name").toUpperCase();
		if(!sysName.startsWith("WINDOWS")){
			rslt="/"+rslt;
		}
        return rslt;
	}
	
    public static boolean responseWrite(HttpServletResponse response,
	    								String str,
	    								String contentType,
	    								String characterEncoding){
    	boolean rslt=true;
    	response.setHeader("Pragma", "no-cache");   
		response.setHeader("Cache-Control", "no-cache");   
		response.setDateHeader("Expires", 0);   

		response.setContentType(contentType); 
		response.setCharacterEncoding(characterEncoding);
		byte[] sm=str.toString().getBytes();
		try { 
	        ServletOutputStream sos;
			sos = response.getOutputStream();			
	        sos.write(sm);
	        sos.close(); 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			rslt=false;
		}
    	return rslt;
    }

    public static boolean responseWriteXml(HttpServletResponse response,
	    								String str,
	    								String characterEncoding){
    	boolean rslt=true;
    	StringBuffer xml=new StringBuffer("");
    	xml.append("<?xml version=\"1.0\" encoding=\"").append(characterEncoding).append("\" ?>\n");
    	xml.append(str);
    	return responseWrite(response,xml.toString(),"text/xml",characterEncoding);
    }

    
    public static String gbkToUtf8(String str){
		try {
			str = new String(str.getBytes("GBK"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;		
	}
    
    public static Date toDate(String date,String dft){
		if(date==null||date=="") return null;

        SimpleDateFormat sdf = new SimpleDateFormat();
		if(isNull(dft)){
			dft ="yyyy-MM-dd HH:mm:ss";
		}else{
	        sdf.applyPattern(dft);			
		}
        Date d=null;
        try {
			d=sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return d;
	}
    public static long toLong(Object o){
    	try{
    		if(DateUtils.isNull(o))o="0";
    		return Long.parseLong(String.valueOf(o));
    	}catch(Exception e){ 
    		e.printStackTrace(); 
    		return 0L;
    	}
    }    
    public static int toInt(Object o){
    	try{
    		if(DateUtils.isNull(o))o="0";
    		return Integer.parseInt(String.valueOf(o));
    	}catch(Exception e){ 
    		e.printStackTrace(); 
    		return 0;
    	}
    }    
    public static float toFloat(Object o){
    	try{
    		if(DateUtils.isNull(o))o="0";
    		return Float.parseFloat(String.valueOf(o));
    	}catch(Exception e){ 
    		e.printStackTrace(); 
    		return 0;
    	}
    }   
    
    public static Boolean toBoolean(Object o){
    	try{
    		if(DateUtils.isNull(o))o="false";
    		return Boolean.parseBoolean(String.valueOf(o));
    	}catch(Exception e){ 
    		e.printStackTrace(); 
    		return false;
    	}
    }  

    public static Boolean isNull(Object o){
    	return isNull(o,true);
    }
    public static Boolean isNull(Object o,boolean includeBlank ){
    	boolean rslt=false;
    	if(o==null)return true;
    	String s=String.valueOf(o);
    	if("NULL".equals(s.toUpperCase()))return true;
    	if(includeBlank && "".equals(s))return true;
    	return rslt;
    }
    
}
